package su.security.filter;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import su.security.entity.SecurityUser;
import su.security.service.SecurityUserService;
import su.tool.SuIntUtils;

public class SecurityFilter implements Filter {
	protected final Log log = LogFactory.getLog(getClass());
	
	     
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException    
	{    
		HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        
        //登录用户
        Object o = request.getSession().getAttribute("sessionUser");
        if(o==null){
        	response.sendRedirect(request.getContextPath() + "/login.jsp");
        	return;
        }
        SecurityUser su = (SecurityUser)o;
        if(su.getId()==0){
        	response.sendRedirect(request.getContextPath() + "/security_error.jsp");
        	return;
        }
        //超级管理员不需要权限验证
        if(su.getUsertype()==2){
        	
        }else{
        	//判断权限
        	log.debug("(--------sutest security begin");
        	log.debug("--------sutest security info,request.getServletPath()===="+request.getServletPath());
        	if(!this.canDo(request,su.getId(), request.getServletPath())){
        		log.debug("--------sutest security info can not do");
        		response.sendRedirect(request.getContextPath() + "/security_error.jsp");
            	return;
        	}
        	log.debug("--------sutest security info can do");
        	log.debug("--------sutest security end)");
        }
        filterChain.doFilter(request, response);
	}
	
	private boolean canDo(HttpServletRequest request,int userId,String url){
		ApplicationContext application = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
		if(application==null)return false;
		SecurityUserService us = (SecurityUserService)application.getBean("securityUserService");
		if(us==null)return false;
		boolean res = us.urlCanDo(userId, url);
		return res;
	}

	public void destroy() {
		
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		
	}    
}    
